package com.ruoyi.common.utils;

import com.ruoyi.common.core.domain.hospital.MrInData;
import com.ruoyi.common.core.domain.hospital.MrInDiagnoss;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 *   解析xml类型 工具类
 */
public class MrInDataUtils {
    public static MrInData getMrInData(String data) throws JAXBException {
        MrInData mrInDataList = null;
        try {

            JAXBContext jaxbContext = JAXBContext.newInstance(MrInData.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            StringReader reader = new StringReader(data);
            mrInDataList = (MrInData) jaxbUnmarshaller.unmarshal(reader);

        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return mrInDataList;
    }
    public static String mrInDataToXML(MrInData person) throws JAXBException, TransformerException {
        JAXBContext jaxbContext = JAXBContext.newInstance(MrInData.class);

        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // 输出格式化
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);



        StringWriter sw = new StringWriter();
        jaxbMarshaller.marshal(person, sw);

        // 获取生成的XML字符串（包含XML声明头）
        String xmlWithDeclaration = sw.toString();

        // 使用Transformer来移除XML声明头
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        // 由于StringSource不是标准API的一部分，我们使用StreamSource并跳过XML声明
        // 我们通过Transformer直接输出到另一个StringWriter来避免XML声明
        Source inputSource = new javax.xml.transform.stream.StreamSource(new java.io.StringReader(xmlWithDeclaration));
        StringWriter outputStringWriter = new StringWriter();
        StreamResult outputStreamResult = new StreamResult(outputStringWriter);

        // 执行转换
        transformer.transform(inputSource, outputStreamResult);

        // 获取最终的XML字符串（不带XML声明头）
        String xmlWithoutDeclaration = outputStringWriter.toString();

        return xmlWithoutDeclaration;
    }
}
